In C, a structure inside another structure, this is known as a nested structure. This allows creating more complex data structures by combining multiple data types together.
To create a nested structure, define a structure inside another structure definition. The inner structure becomes a member of the outer structure, just like any other data type.
struct OuterStruct {
data_type member1;
data_type member2;
// ...
struct InnerStruct {
data_type inner_member1;
data_type inner_member2;
// ...
} inner_instance; // Declare an instance of the inner structure
// ...
} outer_instance; // Declare an instance of the outer structure
#include <stdio.h>
// Define an inner structure
struct Address {
char city[30];
char street[50];
int zip_code;
};
// Define an outer structure containing the inner structure
struct Employee {
int emp_id;
char emp_name[50];
struct Address emp_address; // Nested structure as a member
};
int main() {
// Declare and initialize an instance of the outer structure
struct Employee emp1 = {
.emp_id = 101,
.emp_name = "John Doe",
.emp_address = {
.city = "New York",
.street = "Main Street",
.zip_code = 10001
}
};
// Access and print the information using nested structures
printf("Employee ID: %d\n", emp1.emp_id);
printf("Employee Name: %s\n", emp1.emp_name);
printf("Employee Address: %s, %s, %d\n", emp1.emp_address.street, emp1.emp_address.city, emp1.emp_address.zip_code);
return 0;
}
Employee ID: 101
Employee Name: John Doe
Employee Address: Main Street, New York, 10001
What is a nested structure in C?
What is the purpose of nesting structures in C?
How do you access members of a nested structure in C?